<!--
 * @Author: zxc
 * @Date: 2020-09-13 18:11:43
 * @LastEditTime: 2020-09-15 16:24:58
 * @LastEditors: zxc
 * @Description:
-->
<template>
  <div>
    <slot name='left'></slot>
    <span ref="number" :id="eleId" :class="countClass"></span>
    <slot name="right"></slot>
  </div>
</template>

<script>
import CountUp from 'countup'
export default {
  name: 'CountTo',
  data () {
    return {
      counter: {}
    }
  },
  props: {
    // 初始值
    startVal: {
      type: Number,
      default: 0
    },
    // 终止值
    endVal: {
      type: Number,
      required: true
    },
    // 小数点后保留位数
    decimals: {
      type: Number,
      default: 0
    },
    // 动画延迟开始时间
    delay: {
      type: Number,
      default: 0
    },
    // 渐变时长
    duration: {
      type: Number,
      default: 1
    },
    // 是否使用变速
    useEasing: {
      type: Boolean,
      default: false
    },
    // 是否使用分组
    useGrouping: {
      type: Boolean,
      default: true
    },
    // 分组符号
    separator: {
      type: String,
      default: ','
    },
    // 整数与小数的分割符号
    decimal: {
      type: String,
      default: '.'
    },
    // 样式
    className: {
      type: String,
      default: ''
    }
  },
  computed: {
    eleId () {
      return `count_up_${this._uid}`
    },
    countClass () {
      return ['count-to-number',
        this.className]
    }
  },
  watch: {
    endVal: {
      handler: function (newVal, oldVal) {
        this.counter && this.counter.update && this.counter.update(newVal)
        this.emitEndEvent()
      },
      immediate: true
    }
  },
  methods: {
    getCount () {
      // 获取当前span显示的数值
      return this.$refs.number.innerText
    },
    emitEndEvent () {
      setTimeout(() => {
        this.$nextTick(() => {
          this.$emit('on-animation-end', Number(this.getCount()))
        })
      }, this.duration * 1000 + 5)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.counter = new CountUp(
        this.eleId,
        this.startVal,
        this.endVal,
        this.decimals,
        this.duration,
        {
          useEasing: this.useEasing,
          useGrouping: this.useGrouping,
          separator: this.separator,
          decimal: this.decimal
        }
      )
      setTimeout(() => {
        this.counter.start()
        // this.emitEndEvent()
      }, this.delay)
    })
  }
}
</script>

<style>
</style>
